package com.campus.shop.service.impl;

import com.campus.shop.common.Errors;
import com.campus.shop.controller.web.vo.UserAddressVo;
import com.campus.shop.entity.UserAddress;
import com.campus.shop.exception.ServiceException;
import com.campus.shop.mapper.UserAddressMapper;
import com.campus.shop.service.UserAddressService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.campus.shop.common.ConstantProperties;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * 服务实现类
 *
 * @author xr
 * @since 2024-01-16 15:12:47
 */
@Service
public class UserAddressServiceImpl extends ServiceImpl<UserAddressMapper, UserAddress> implements UserAddressService {
    @Resource
    private UserAddressMapper userAddressMapper;

    @Override
    public Boolean insertUserAddress(UserAddress userAddress) {
        return this.save(userAddress);
    }

    @Override
    public Boolean updateUserAddress(UserAddress userAddress) {
        return this.updateById(userAddress);
    }

    @Override
    public Boolean deleteUserAddress(Long id) {
        return this.removeById(id);
    }

    @Override
    public UserAddress queryById(Long id) {
        return this.getById(id);
    }

    @Override
    public void checkAddress(UserAddressVo userAddress, Integer userId) {
        QueryWrapper<UserAddress> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id",userId);
        wrapper.eq("status", ConstantProperties.normalStatus);
        Integer count = Math.toIntExact(userAddressMapper.selectCount(wrapper));
        if(count > ConstantProperties.addressCount || count == ConstantProperties.addressCount){
            throw new ServiceException(Errors.LIMIT_ADDRESS_NUM);
        }
        if(userAddress.getIsDefault()){
            userAddressMapper.updateAllByUserId(userId);
        }
    }
}

